package com.spa.infrastructure.util;

import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;

public class UrlUtil {

    private static final String domain = "https://qiniu.spadj.com/";
    public static String handleUrl(String url, String split) {
        StringJoiner stringJoiner = new StringJoiner(split);
        if (StringUtils.isNotEmpty(url)) {
            String[] arr = url.split(split);
            for (String s : arr) {
                if (s.contains(domain)) {
                    int begin = domain.length();
                    int end = s.indexOf("?");
                    stringJoiner.add(s.substring(begin, end));
                } else {
                    stringJoiner.add(s);
                }
            }
        }
        return stringJoiner.toString();
    }

    public static List<String> handleUrlList(List<String> urls) {
        List<String> list = new ArrayList<>();
        for (String s : urls) {
            if (s.contains(domain)) {
                int begin = domain.length();
                int end = s.indexOf("?");
                list.add(s.substring(begin, end));
            } else {
                list.add(s);
            }
        }
        return list;
    }

    public static String resolveShortUrl(String shortUrl) {
        String redirectUrl = null;
        try {
            URL url = new URL(shortUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setInstanceFollowRedirects(false); // 禁止自动重定向
            connection.setConnectTimeout(3000); // 设置连接超时时间
            connection.setReadTimeout(3000); // 设置读取超时时间
            connection.setRequestMethod("GET"); // 设置请求方法

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM) {
                // 获取重定向的URL
                String newUrl = connection.getHeaderField("Location");
                // 递归解析新的短链接，直到找不到重定向
                redirectUrl = resolveShortUrl(newUrl);
            } else {
                // 没有重定向，返回原链接
                redirectUrl = shortUrl;
            }

            connection.disconnect(); // 关闭连接

        } catch (Exception e) {
            e.printStackTrace();
        }
        return redirectUrl;
    }

}
